<template>
  <div class="content-area">
    <!-- 筛选卡片 -->
    <div class="filter-card">
      <div class="filter-row">
        <div class="filter-item">
          <div class="filter-label">患者姓名</div>
          <el-input
            v-model="filters.patientName"
            placeholder="请输入患者姓名"
            clearable
          />
        </div>
        <div class="filter-item">
          <div class="filter-label">患者ID</div>
          <el-input
            v-model="filters.patientId"
            placeholder="请输入患者ID"
            clearable
          />
        </div>
        <div class="filter-item">
          <div class="filter-label">手机号码</div>
          <el-input
            v-model="filters.phone"
            placeholder="请输入手机号码"
            clearable
          />
        </div>
        <div class="filter-item">
          <div class="filter-label">性别</div>
          <el-select
            v-model="filters.gender"
            placeholder="请选择性别"
            clearable
          >
            <el-option label="男" value="male" />
            <el-option label="女" value="female" />
          </el-select>
        </div>
        <div class="filter-item">
          <div class="filter-label">年龄范围</div>
          <div class="age-range">
            <el-input-number
              v-model="filters.minAge"
              :min="0"
              :max="120"
              placeholder="最小"
              controls-position="right"
            />
            <span class="range-separator">-</span>
            <el-input-number
              v-model="filters.maxAge"
              :min="0"
              :max="120"
              placeholder="最大"
              controls-position="right"
            />
          </div>
        </div>
      </div>
      <div class="action-buttons">
        <el-button @click="resetFilters">重置</el-button>
        <el-button type="primary" @click="searchPatients">查询</el-button>
        <el-button type="success" @click="showAddPatientDialog">
          <el-icon><Plus /></el-icon>
          新增患者
        </el-button>
      </div>
    </div>

    <!-- 患者表格 -->
    <div class="patient-table">
      <div class="table-header">
        <div class="table-title">患者列表</div>
        <div class="table-tools">
          <el-button type="primary" @click="exportData">
            <el-icon><Document /></el-icon>
            导出数据
          </el-button>
          <el-button @click="refreshData">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </div>

      <el-table
        :data="pagedPatients"
        style="width: 100%"
        stripe
        border
        v-loading="loading"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="patientId" label="患者ID" width="120" fixed />
        <el-table-column label="患者信息" min-width="180">
          <template #default="{ row }">
            <div class="patient-info">
              <div class="patient-avatar">
                <el-icon><User /></el-icon>
              </div>
              <div>
                <div class="patient-name">{{ row.name }}</div>
                <div class="patient-meta">
                  {{ row.gender === "male" ? "男" : "女" }} · {{ row.age }}岁
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="手机号码" width="150" />
        <el-table-column prop="idCard" label="身份证号" width="200" />
        <el-table-column
          prop="address"
          label="居住地址"
          min-width="200"
          show-overflow-tooltip
        />
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag
              :type="row.status === 'active' ? 'success' : 'info'"
              size="small"
            >
              {{ row.status === "active" ? "活跃" : "非活跃" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons-cell">
              <el-button size="small" @click="viewPatientDetails(row)"
                >详情</el-button
              >
              <el-button size="small" type="primary" @click="editPatient(row)">
                编辑
              </el-button>
              <el-button size="small" type="danger" @click="deletePatient(row)">
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="filteredPatients.length"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
  <!-- 新增/编辑患者对话框 -->
  <el-dialog
    v-model="patientDialog.visible"
    :title="patientDialog.isEdit ? '编辑患者信息' : '新增患者'"
    width="600px"
    :close-on-click-modal="false"
  >
    <el-form
      :model="patientForm"
      label-width="100px"
      :rules="patientRules"
      ref="patientFormRef"
    >
      <el-form-item label="患者姓名" prop="name">
        <el-input v-model="patientForm.name" placeholder="请输入患者姓名" />
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-radio-group v-model="patientForm.gender">
          <el-radio label="male">男</el-radio>
          <el-radio label="female">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="年龄" prop="age">
        <el-input-number v-model="patientForm.age" :min="0" :max="120" />
      </el-form-item>
      <el-form-item label="手机号码" prop="phone">
        <el-input v-model="patientForm.phone" placeholder="请输入手机号码" />
      </el-form-item>
      <el-form-item label="身份证号" prop="idCard">
        <el-input v-model="patientForm.idCard" placeholder="请输入身份证号" />
      </el-form-item>
      <el-form-item label="居住地址" prop="address">
        <el-input v-model="patientForm.address" placeholder="请输入居住地址" />
      </el-form-item>
      <el-form-item label="过敏史" prop="allergyHistory">
        <el-input
          v-model="patientForm.allergyHistory"
          type="textarea"
          :rows="3"
          placeholder="请输入过敏史，如无请填写'无'"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="patientDialog.visible = false">取消</el-button>
      <el-button type="primary" @click="submitPatientForm">确认</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";

const sidebarOpen = ref(false);
const loading = ref(false);
const filters = reactive({
  patientName: "",
  patientId: "",
  phone: "",
  gender: "",
  minAge: null,
  maxAge: null,
});

const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});

// 患者数据
const patients = ref([]);

// 患者对话框相关
const patientDialog = reactive({
  visible: false,
  isEdit: false,
});

const patientForm = reactive({
  id: "",
  name: "",
  gender: "male",
  age: 30,
  phone: "",
  idCard: "",
  address: "",
  allergyHistory: "无",
  status: "active",
});

const patientRules = {
  name: [{ required: true, message: "请输入患者姓名", trigger: "blur" }],
  gender: [{ required: true, message: "请选择性别", trigger: "change" }],
  age: [{ required: true, message: "请输入年龄", trigger: "blur" }],
  phone: [
    { required: true, message: "请输入手机号码", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
  idCard: [
    { required: true, message: "请输入身份证号", trigger: "blur" },
    {
      pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
      message: "请输入正确的身份证号",
      trigger: "blur",
    },
  ],
  address: [{ required: true, message: "请输入居住地址", trigger: "blur" }],
};

const patientFormRef = ref(null);

const toggleSidebar = () => {
  sidebarOpen.value = !sidebarOpen.value;
};

const resetFilters = () => {
  filters.patientName = "";
  filters.patientId = "";
  filters.phone = "";
  filters.gender = "";
  filters.minAge = null;
  filters.maxAge = null;
  loadPatients();
};

const searchPatients = () => {
  pagination.currentPage = 1;
  loadPatients();
};

// 计算属性 - 筛选后的患者
const filteredPatients = computed(() => {
  let result = [...patients.value];

  // 按患者姓名筛选
  if (filters.patientName) {
    result = result.filter((item) => item.name.includes(filters.patientName));
  }

  // 按患者ID筛选
  if (filters.patientId) {
    result = result.filter((item) =>
      item.patientId.includes(filters.patientId)
    );
  }

  // 按手机号码筛选
  if (filters.phone) {
    result = result.filter((item) => item.phone.includes(filters.phone));
  }

  // 按性别筛选
  if (filters.gender) {
    result = result.filter((item) => item.gender === filters.gender);
  }

  // 按最小年龄筛选
  if (filters.minAge !== null) {
    result = result.filter((item) => item.age >= filters.minAge);
  }

  // 按最大年龄筛选
  if (filters.maxAge !== null) {
    result = result.filter((item) => item.age <= filters.maxAge);
  }

  return result;
});

// 计算属性 - 分页数据
const pagedPatients = computed(() => {
  const start = (pagination.currentPage - 1) * pagination.pageSize;
  const end = start + pagination.pageSize;
  return filteredPatients.value.slice(start, end);
});

const loadPatients = async () => {
  loading.value = true;

  try {
    // 模拟API调用延迟
    await new Promise((resolve) => setTimeout(resolve, 500));

    // 模拟数据
    const mockData = [
      {
        id: "10001",
        patientId: "PT20230001",
        name: "张先生",
        gender: "male",
        age: 45,
        phone: "13800138001",
        idCard: "11010119800101001X",
        address: "北京市朝阳区建国路88号",
        allergyHistory: "青霉素过敏",
        status: "active",
        createTime: "2023-01-15",
      },
      {
        id: "10002",
        patientId: "PT20230002",
        name: "王女士",
        gender: "female",
        age: 32,
        phone: "13800138002",
        idCard: "11010119910101002X",
        address: "北京市海淀区中关村大街1号",
        allergyHistory: "无",
        status: "active",
        createTime: "2023-02-20",
      },
      {
        id: "10003",
        patientId: "PT20230003",
        name: "李先生",
        gender: "male",
        age: 58,
        phone: "13800138003",
        idCard: "11010119650101003X",
        address: "北京市西城区西长安街1号",
        allergyHistory: "海鲜过敏",
        status: "active",
        createTime: "2023-03-10",
      },
      {
        id: "10004",
        patientId: "PT20230004",
        name: "赵女士",
        gender: "female",
        age: 29,
        phone: "13800138004",
        idCard: "11010119940101004X",
        address: "北京市东城区东长安街1号",
        allergyHistory: "无",
        status: "inactive",
        createTime: "2023-04-05",
      },
      {
        id: "10005",
        patientId: "PT20230005",
        name: "刘先生",
        gender: "male",
        age: 50,
        phone: "13800138005",
        idCard: "11010119730101005X",
        address: "北京市丰台区丰台路1号",
        allergyHistory: "花粉过敏",
        status: "active",
        createTime: "2023-05-15",
      },
      {
        id: "10006",
        patientId: "PT20230006",
        name: "陈女士",
        gender: "female",
        age: 35,
        phone: "13800138006",
        idCard: "11010119880101006X",
        address: "北京市石景山区石景山路1号",
        allergyHistory: "无",
        status: "active",
        createTime: "2023-06-10",
      },
      {
        id: "10007",
        patientId: "PT20230007",
        name: "林先生",
        gender: "male",
        age: 42,
        phone: "13800138007",
        idCard: "11010119810101007X",
        address: "北京市通州区新华大街1号",
        allergyHistory: "无",
        status: "active",
        createTime: "2023-07-15",
      },
      {
        id: "10008",
        patientId: "PT20230008",
        name: "黄女士",
        gender: "female",
        age: 28,
        phone: "13800138008",
        idCard: "11010119950101008X",
        address: "北京市昌平区府学路1号",
        allergyHistory: "无",
        status: "inactive",
        createTime: "2023-08-20",
      },
      {
        id: "10009",
        patientId: "PT20230009",
        name: "吴先生",
        gender: "male",
        age: 55,
        phone: "13800138009",
        idCard: "11010119680101009X",
        address: "北京市大兴区兴政街1号",
        allergyHistory: "无",
        status: "active",
        createTime: "2023-09-05",
      },
      {
        id: "10010",
        patientId: "PT20230010",
        name: "郑女士",
        gender: "female",
        age: 38,
        phone: "13800138010",
        idCard: "11010119850101010X",
        address: "北京市房山区政通路1号",
        allergyHistory: "无",
        status: "active",
        createTime: "2023-10-15",
      },
    ];

    patients.value = mockData;
    pagination.total = mockData.length;
  } catch (error) {
    ElMessage.error("加载患者数据失败");
    console.error("加载患者数据失败:", error);
  } finally {
    loading.value = false;
  }
};

const handleSizeChange = (size) => {
  pagination.pageSize = size;
};

const handleCurrentChange = (page) => {
  pagination.currentPage = page;
};

const viewPatientDetails = (patient) => {
  ElMessage.info(`查看患者详情：${patient.name}`);
  // 实际项目中这里可以跳转到详情页或打开详情弹窗
};

const editPatient = (patient) => {
  Object.assign(patientForm, patient);
  patientDialog.isEdit = true;
  patientDialog.visible = true;
};

const deletePatient = (patient) => {
  ElMessageBox.confirm(
    `确定要删除患者 ${patient.name} 吗？此操作不可恢复！`,
    "删除确认",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(() => {
      // 模拟删除操作
      patients.value = patients.value.filter((p) => p.id !== patient.id);
      ElMessage.success("删除成功");
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

const showAddPatientDialog = () => {
  // 重置表单
  Object.assign(patientForm, {
    id: "",
    name: "",
    gender: "male",
    age: 30,
    phone: "",
    idCard: "",
    address: "",
    allergyHistory: "无",
    status: "active",
  });
  patientDialog.isEdit = false;
  patientDialog.visible = true;
};

const submitPatientForm = async () => {
  try {
    await patientFormRef.value.validate();

    // 模拟保存操作
    if (patientDialog.isEdit) {
      // 更新患者
      const index = patients.value.findIndex((p) => p.id === patientForm.id);
      if (index !== -1) {
        patients.value[index] = { ...patientForm };
      }
      ElMessage.success("患者信息更新成功");
    } else {
      // 新增患者
      const newPatient = {
        ...patientForm,
        id: `100${patients.value.length + 1}`,
        patientId: `PT202300${patients.value.length + 1}`,
        createTime: new Date().toISOString().split("T")[0],
      };
      patients.value.unshift(newPatient);
      ElMessage.success("患者添加成功");
    }

    patientDialog.visible = false;
    loadPatients();
  } catch (error) {
    console.error("表单验证失败:", error);
  }
};

const exportData = () => {
  ElMessage.success("数据导出成功");
};

const refreshData = () => {
  loadPatients();
  ElMessage.success("数据已刷新");
};

onMounted(() => {
  loadPatients();
});
</script>

<style lang="scss" scoped>
/* 主内容区域样式 */
.content-area {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
  background-color: #f5f7fa;
  height: 0;  // 添加这行
  min-height: 100%;  // 添加这行
  overflow-y: auto;  // 确保有这行
}

/* 患者管理页面特定样式 */
.filter-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 24px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

.filter-row {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin-bottom: 16px;
}

.filter-item {
  display: flex;
  flex-direction: column;
  min-width: 200px;
  flex: 1;
}

.age-range {
  display: flex;
  align-items: center;
}

.range-separator {
  margin: 0 8px;
  color: #606266;
}

.filter-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.action-buttons {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  margin-top: 16px;
}

.patient-table {
  background: white;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.table-title {
  font-size: 18px;
  font-weight: 600;
}

.table-tools {
  display: flex;
  gap: 12px;
}

.action-buttons-cell {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.pagination {
  margin-top: 24px;
  display: flex;
  justify-content: flex-end;
}

.patient-info {
  display: flex;
  align-items: center;
}

.patient-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  color: #1a75bc;
}

.patient-name {
  font-weight: 500;
}

.patient-meta {
  font-size: 12px;
  color: #909399;
  margin-top: 2px;
}


</style>